/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package daos;

import daos.exceptions.IllegalOrphanException;
import daos.exceptions.NonexistentEntityException;
import daos.exceptions.PreexistingEntityException;
import daos.exceptions.RollbackFailureException;
import entidades.Deportista;
import java.io.Serializable;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import entidades.Disciplina;
import java.util.ArrayList;
import java.util.Collection;
import entidades.DeportistaCompetencia;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.transaction.UserTransaction;

/**
 *
 * @author usuario
 */
public class DeportistaJpaController implements Serializable {

    public DeportistaJpaController(UserTransaction utx, EntityManagerFactory emf) {
        this.utx = utx;
        this.emf = emf;
    }
    private UserTransaction utx = null;
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public void create(Deportista deportista) throws PreexistingEntityException, RollbackFailureException, Exception {
        if (deportista.getDisciplinaCollection() == null) {
            deportista.setDisciplinaCollection(new ArrayList<Disciplina>());
        }
        if (deportista.getDeportistaCompetenciaCollection() == null) {
            deportista.setDeportistaCompetenciaCollection(new ArrayList<DeportistaCompetencia>());
        }
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Collection<Disciplina> attachedDisciplinaCollection = new ArrayList<Disciplina>();
            for (Disciplina disciplinaCollectionDisciplinaToAttach : deportista.getDisciplinaCollection()) {
                disciplinaCollectionDisciplinaToAttach = em.getReference(disciplinaCollectionDisciplinaToAttach.getClass(), disciplinaCollectionDisciplinaToAttach.getIdDisciplina());
                attachedDisciplinaCollection.add(disciplinaCollectionDisciplinaToAttach);
            }
            deportista.setDisciplinaCollection(attachedDisciplinaCollection);
            Collection<DeportistaCompetencia> attachedDeportistaCompetenciaCollection = new ArrayList<DeportistaCompetencia>();
            for (DeportistaCompetencia deportistaCompetenciaCollectionDeportistaCompetenciaToAttach : deportista.getDeportistaCompetenciaCollection()) {
                deportistaCompetenciaCollectionDeportistaCompetenciaToAttach = em.getReference(deportistaCompetenciaCollectionDeportistaCompetenciaToAttach.getClass(), deportistaCompetenciaCollectionDeportistaCompetenciaToAttach.getDeportistaCompetenciaPK());
                attachedDeportistaCompetenciaCollection.add(deportistaCompetenciaCollectionDeportistaCompetenciaToAttach);
            }
            deportista.setDeportistaCompetenciaCollection(attachedDeportistaCompetenciaCollection);
            em.persist(deportista);
            for (Disciplina disciplinaCollectionDisciplina : deportista.getDisciplinaCollection()) {
                disciplinaCollectionDisciplina.getDeportistaCollection().add(deportista);
                disciplinaCollectionDisciplina = em.merge(disciplinaCollectionDisciplina);
            }
            for (DeportistaCompetencia deportistaCompetenciaCollectionDeportistaCompetencia : deportista.getDeportistaCompetenciaCollection()) {
                Deportista oldDeportistaOfDeportistaCompetenciaCollectionDeportistaCompetencia = deportistaCompetenciaCollectionDeportistaCompetencia.getDeportista();
                deportistaCompetenciaCollectionDeportistaCompetencia.setDeportista(deportista);
                deportistaCompetenciaCollectionDeportistaCompetencia = em.merge(deportistaCompetenciaCollectionDeportistaCompetencia);
                if (oldDeportistaOfDeportistaCompetenciaCollectionDeportistaCompetencia != null) {
                    oldDeportistaOfDeportistaCompetenciaCollectionDeportistaCompetencia.getDeportistaCompetenciaCollection().remove(deportistaCompetenciaCollectionDeportistaCompetencia);
                    oldDeportistaOfDeportistaCompetenciaCollectionDeportistaCompetencia = em.merge(oldDeportistaOfDeportistaCompetenciaCollectionDeportistaCompetencia);
                }
            }
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            if (findDeportista(deportista.getCedula()) != null) {
                throw new PreexistingEntityException("Deportista " + deportista + " already exists.", ex);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void edit(Deportista deportista) throws IllegalOrphanException, NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Deportista persistentDeportista = em.find(Deportista.class, deportista.getCedula());
            Collection<Disciplina> disciplinaCollectionOld = persistentDeportista.getDisciplinaCollection();
            Collection<Disciplina> disciplinaCollectionNew = deportista.getDisciplinaCollection();
            Collection<DeportistaCompetencia> deportistaCompetenciaCollectionOld = persistentDeportista.getDeportistaCompetenciaCollection();
            Collection<DeportistaCompetencia> deportistaCompetenciaCollectionNew = deportista.getDeportistaCompetenciaCollection();
            List<String> illegalOrphanMessages = null;
            for (DeportistaCompetencia deportistaCompetenciaCollectionOldDeportistaCompetencia : deportistaCompetenciaCollectionOld) {
                if (!deportistaCompetenciaCollectionNew.contains(deportistaCompetenciaCollectionOldDeportistaCompetencia)) {
                    if (illegalOrphanMessages == null) {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("You must retain DeportistaCompetencia " + deportistaCompetenciaCollectionOldDeportistaCompetencia + " since its deportista field is not nullable.");
                }
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            Collection<Disciplina> attachedDisciplinaCollectionNew = new ArrayList<Disciplina>();
            for (Disciplina disciplinaCollectionNewDisciplinaToAttach : disciplinaCollectionNew) {
                disciplinaCollectionNewDisciplinaToAttach = em.getReference(disciplinaCollectionNewDisciplinaToAttach.getClass(), disciplinaCollectionNewDisciplinaToAttach.getIdDisciplina());
                attachedDisciplinaCollectionNew.add(disciplinaCollectionNewDisciplinaToAttach);
            }
            disciplinaCollectionNew = attachedDisciplinaCollectionNew;
            deportista.setDisciplinaCollection(disciplinaCollectionNew);
            Collection<DeportistaCompetencia> attachedDeportistaCompetenciaCollectionNew = new ArrayList<DeportistaCompetencia>();
            for (DeportistaCompetencia deportistaCompetenciaCollectionNewDeportistaCompetenciaToAttach : deportistaCompetenciaCollectionNew) {
                deportistaCompetenciaCollectionNewDeportistaCompetenciaToAttach = em.getReference(deportistaCompetenciaCollectionNewDeportistaCompetenciaToAttach.getClass(), deportistaCompetenciaCollectionNewDeportistaCompetenciaToAttach.getDeportistaCompetenciaPK());
                attachedDeportistaCompetenciaCollectionNew.add(deportistaCompetenciaCollectionNewDeportistaCompetenciaToAttach);
            }
            deportistaCompetenciaCollectionNew = attachedDeportistaCompetenciaCollectionNew;
            deportista.setDeportistaCompetenciaCollection(deportistaCompetenciaCollectionNew);
            deportista = em.merge(deportista);
            for (Disciplina disciplinaCollectionOldDisciplina : disciplinaCollectionOld) {
                if (!disciplinaCollectionNew.contains(disciplinaCollectionOldDisciplina)) {
                    disciplinaCollectionOldDisciplina.getDeportistaCollection().remove(deportista);
                    disciplinaCollectionOldDisciplina = em.merge(disciplinaCollectionOldDisciplina);
                }
            }
            for (Disciplina disciplinaCollectionNewDisciplina : disciplinaCollectionNew) {
                if (!disciplinaCollectionOld.contains(disciplinaCollectionNewDisciplina)) {
                    disciplinaCollectionNewDisciplina.getDeportistaCollection().add(deportista);
                    disciplinaCollectionNewDisciplina = em.merge(disciplinaCollectionNewDisciplina);
                }
            }
            for (DeportistaCompetencia deportistaCompetenciaCollectionNewDeportistaCompetencia : deportistaCompetenciaCollectionNew) {
                if (!deportistaCompetenciaCollectionOld.contains(deportistaCompetenciaCollectionNewDeportistaCompetencia)) {
                    Deportista oldDeportistaOfDeportistaCompetenciaCollectionNewDeportistaCompetencia = deportistaCompetenciaCollectionNewDeportistaCompetencia.getDeportista();
                    deportistaCompetenciaCollectionNewDeportistaCompetencia.setDeportista(deportista);
                    deportistaCompetenciaCollectionNewDeportistaCompetencia = em.merge(deportistaCompetenciaCollectionNewDeportistaCompetencia);
                    if (oldDeportistaOfDeportistaCompetenciaCollectionNewDeportistaCompetencia != null && !oldDeportistaOfDeportistaCompetenciaCollectionNewDeportistaCompetencia.equals(deportista)) {
                        oldDeportistaOfDeportistaCompetenciaCollectionNewDeportistaCompetencia.getDeportistaCompetenciaCollection().remove(deportistaCompetenciaCollectionNewDeportistaCompetencia);
                        oldDeportistaOfDeportistaCompetenciaCollectionNewDeportistaCompetencia = em.merge(oldDeportistaOfDeportistaCompetenciaCollectionNewDeportistaCompetencia);
                    }
                }
            }
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = deportista.getCedula();
                if (findDeportista(id) == null) {
                    throw new NonexistentEntityException("The deportista with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws IllegalOrphanException, NonexistentEntityException, RollbackFailureException, Exception {
        EntityManager em = null;
        try {
            utx.begin();
            em = getEntityManager();
            Deportista deportista;
            try {
                deportista = em.getReference(Deportista.class, id);
                deportista.getCedula();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The deportista with id " + id + " no longer exists.", enfe);
            }
            List<String> illegalOrphanMessages = null;
            Collection<DeportistaCompetencia> deportistaCompetenciaCollectionOrphanCheck = deportista.getDeportistaCompetenciaCollection();
            for (DeportistaCompetencia deportistaCompetenciaCollectionOrphanCheckDeportistaCompetencia : deportistaCompetenciaCollectionOrphanCheck) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("This Deportista (" + deportista + ") cannot be destroyed since the DeportistaCompetencia " + deportistaCompetenciaCollectionOrphanCheckDeportistaCompetencia + " in its deportistaCompetenciaCollection field has a non-nullable deportista field.");
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            Collection<Disciplina> disciplinaCollection = deportista.getDisciplinaCollection();
            for (Disciplina disciplinaCollectionDisciplina : disciplinaCollection) {
                disciplinaCollectionDisciplina.getDeportistaCollection().remove(deportista);
                disciplinaCollectionDisciplina = em.merge(disciplinaCollectionDisciplina);
            }
            em.remove(deportista);
            utx.commit();
        } catch (Exception ex) {
            try {
                utx.rollback();
            } catch (Exception re) {
                throw new RollbackFailureException("An error occurred attempting to roll back the transaction.", re);
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Deportista> findDeportistaEntities() {
        return findDeportistaEntities(true, -1, -1);
    }

    public List<Deportista> findDeportistaEntities(int maxResults, int firstResult) {
        return findDeportistaEntities(false, maxResults, firstResult);
    }

    private List<Deportista> findDeportistaEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Deportista.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Deportista findDeportista(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Deportista.class, id);
        } finally {
            em.close();
        }
    }

    public int getDeportistaCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Deportista> rt = cq.from(Deportista.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }
    
}
